package com.heima.comment.service.impl;

import com.heima.comment.dto.*;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentRepay;
import com.heima.comment.entity.ApCommentRepayLike;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentRepayService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppUserThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ICommentRepayServiceImpl implements ICommentRepayService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult saveRepay(CommentRepaySaveDto dto) {
        //判断登录
        User user = AppUserThreadLocal.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //判断参数
        if (dto == null || dto.getCommentId() == null || StringUtils.isEmpty(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApCommentRepay apCommentRepay= new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getUserId());
        ResponseResult<ApUser> userResponseResult = userFeign.findUserById(user.getUserId());
        if (userResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApUser apUser = userResponseResult.getData();
            if (apUser != null) {
                apCommentRepay.setAuthorName(apUser.getName());
            }
        }
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        mongoTemplate.save(apCommentRepay);
        Query queryComment = new Query(Criteria.where("id").is(dto.getCommentId()));
        Update update = new Update();
        update.inc("reply");
        mongoTemplate.updateFirst(queryComment,update,ApComment.class);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult saveRepayLike(CommentRepayLikeDto dto) {
        //判断登录
        User user = AppUserThreadLocal.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询是否有点赞记录
        Query query = new Query();
        query.addCriteria(Criteria.where("commentRepayId").is(dto.getCommentRepayId()));
        query.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        ApCommentRepayLike one = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (one == null) {
            //构建对象
            ApCommentRepayLike apCommentLike = new ApCommentRepayLike();
            apCommentLike.setAuthorId(user.getUserId());
            apCommentLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentLike);
            //增加点赞数
            Query queryComment = new Query(Criteria.where("id").is(dto.getCommentRepayId()));
            Update update = new Update();
            update.inc("likes");
            mongoTemplate.updateFirst(queryComment, update, ApCommentRepay.class);
        } else {
            //判断状态
            if (one.getOperation() != dto.getOperation()) {
                one.setOperation(dto.getOperation());
                mongoTemplate.save(one);

                int inc = 1;
                if (dto.getOperation() == 1) {
                    //取消点赞
                    inc = -1;
                }
                Query queryComment = new Query(Criteria.where("id").is(dto.getCommentRepayId()));
                Update update = new Update();
                update.inc("likes",inc);
                mongoTemplate.updateFirst(queryComment, update, ApCommentRepay.class);
            }
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult loadRepayLike(CommentRepayDto dto) {
        //构建分页查询
        Query query = new Query();
        query.addCriteria(Criteria.where("commentId").is(dto.getCommentId()));
        Pageable pageAble = PageRequest.of(0, 10, Sort.Direction.DESC, "createdTime");
        query.with(pageAble);
        query.addCriteria(Criteria.where("createdTime").lt(dto.getMinDate()));
        List<ApCommentRepay> commentList = mongoTemplate.find(query, ApCommentRepay.class);

        //判断用户是否登录
        User user = AppUserThreadLocal.get();

        List<ApCommentRepayVo> apCommentRepayVoList = new ArrayList<>();
        List<String> idList = new ArrayList<>();
        for (ApCommentRepay apComment : commentList) {
            idList.add(apComment.getId());
            ApCommentRepayVo vo = new ApCommentRepayVo();
            BeanUtils.copyProperties(apComment,vo);
            vo.setOperation(1);
            apCommentRepayVoList.add(vo);
        }
        if (user == null) {
            return ResponseResult.okResult(apCommentRepayVoList);
        }
        //如果登录了，拿到用户评论是否点赞
        Query queryLike = new Query();
        queryLike.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        queryLike.addCriteria(Criteria.where("commentRepayId").in(idList));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(queryLike, ApCommentRepayLike.class);
        List<String> likeId = new ArrayList<>();
        for (ApCommentRepayLike apCommentLike : apCommentRepayLikes) {
            if (apCommentLike.getOperation()==0){
                likeId.add(apCommentLike.getCommentRepayId());
            }
        }
        for (ApCommentRepayVo apCommentVo : apCommentRepayVoList) {
            if (likeId.contains(apCommentVo.getId())){
                apCommentVo.setOperation(0);
            }
        }
        return ResponseResult.okResult(apCommentRepayVoList);
    }
}
